<script setup>
import { siteTitle } from "@/config/settings";
import { getMsg } from "@/api/user";
import { userLogin } from "@/api/login";
import { showToast } from "vant";
import { useCountDown } from "@vant/use";
import { getOpenid, setOpenid, setStorage } from "@/utils/local";

const phone = ref("");
const msgCode = ref("");
const checked = ref(false);
const { reset, start, current } = useCountDown({
	time: 60 * 1000,
});
const visible = ref(true);
const onMsg = async (val) => {
	if (!phone.value) {
		showToast("手机号不能为空");
		return;
	}
	if (val > 0) return;
	visible.value = false;
	reset();
	start();
	await getMsg({
		phoneNum: phone.value,
	});
};
/* 登录 */
const router = useRouter();

const onSubmit = async () => {
	if (!phone.value) {
		showToast("手机号码不能为空");
		return;
	}
	if (phone.value.length !== 11) {
		showToast("手机号码格式不正确");
		return;
	}
	if (!msgCode.value) {
		showToast("验证码不能为空");
		return;
	}
	if (!checked.value) {
		showToast("请先阅读并勾选协议");
		return;
	}
	const { code, data, msg } = await userLogin({
		phoneNum: phone.value,
		msgCode: msgCode.value,
		wchatOpenid: getOpenid(),
	});
	if (code === "0000") {
		showToast("登录成功");
		setOpenid(data.wchatOpenid);
		setStorage("info", data);
		const { redirect, ...othersQuery } = router.currentRoute.value.query;
		router.replace({
			name: redirect || "home",
			query: {
				...othersQuery,
			},
		});
	} else {
		showToast(msg);
	}
};
</script>
<template>
	<div
		class="flex h-full w-full flex-col items-center bg-white bg-[url(https://oss.dingdongdr.com/static/rests/login.png)] bg-[length:100%_auto] bg-bottom bg-no-repeat pt-[60px]"
	>
		<van-image width="17.5vw" height="17.5vw" src="https://oss.dingdongdr.com/static/rests/dingdong.png" />
		<div class="mb-[50px] mt-[20px] text-[18px] font-[500]">{{ siteTitle }}</div>
		<div class="w-[290px]">手机号</div>
		<van-field
			v-model="phone"
			class="custom"
			:border="false"
			maxlength="11"
			type="tel"
			placeholder="请输入您的手机号"
		/>
		<div class="mt-[12px] w-[290px]">验证码</div>
		<van-field v-model="msgCode" class="custom" :border="false" maxlength="6" type="tel" placeholder="请输入短信验证码">
			<template #right-icon>
				<div v-show="visible" @click="onMsg" class="text-[#5288f5]">获取验证码</div>
				<div v-show="!visible" class="text-[#5288f5]" @click="onMsg(current.seconds)">
					重新获取<span v-if="current.seconds !== 0">{{ current.seconds }}s</span>
				</div>
			</template>
		</van-field>
		<div class="mt-[16px] flex w-[290px] items-center">
			<van-checkbox v-model="checked" icon-size="5vw" /> &nbsp;已阅读并同意
			<span class="text-[#5288f5]">《叮咚依生用户协议》</span>
		</div>
		<div
			class="mt-[50px] w-[290px] rounded-[20px] bg-gradient-to-r from-[#4d90f5] to-[#357efe] py-[10px] text-center text-[#ffffff]"
			@click="onSubmit"
		>
			登录
		</div>
	</div>
</template>

<style lang="scss" scoped>
.custom {
	background: transparent;
	width: 290px;
	padding: 6px 0 4px 0;
	&::after {
		border: none;
	}
	border-bottom: 1px solid #e5e7eb;
}
</style>
